<template>
  <div class="IlmsForm h-full">
    <div class="IlmsForm-content h-full">
      <BasicForm ref="formRef" @register="registerForm" class="h-full" :class="isFlow? 'p-3' : ''">
        <template #contractSigningPartyA="{ model, field }">
          <MerchantSelect
            v-model:value="model[field]"
            v-model:label="model.contractSigningPartyAName"
            :options="[{ name: model.contractSigningPartyAName, code: model.contractSigningPartyA }]"
            placeholder="请选择合同签署甲方"
            :style="{ width: '100%' }"
            @change="validateFields([field])"
            allow-clear
          />
        </template>
        <template #projectManager="{ model, field }">
          <!-- 所选乙方所有人员 -->
          <PartyBStaffSelect
            v-model:value="model[field]"
            v-model:label="model.projectManagerName"
            :options="[{ staffName: model.projectManagerName, staffId: model[field] }]"
            placeholder="请选择子项目经理"
            title="请选择子项目经理"
            :disabled="!isEdit"
            :searchInfo="{
              orgId: partyBId,
            }"
            allow-clear
          />
        </template>
        <template #contractAnnexDraft="{ model, field }">
          <JnpfUploadFile
            :limit="1"
            :disabled="!isMine"
            v-model:value="model[field]"
            @change="onUploadFileChange"
          />
        </template>
        <template #contractPaymentTerms="{ model, field }">
          <div class="title-tip">
            <TableTitle title="支付条款明细" />
            <div class="tip-container">
              <a-tag 
                v-show="showAutoBisectButton(model, field)" 
                color="orange"
                class="flex-tag"
              >
                {{ `分包比例自动分配，最后一项的分包比例由"内部${ isCommission ? '委托' : '分包' }金额"扣减计算，使得"内部分包合同对应金额"累计和等于"内部${ isCommission ? '委托' : '分包' }金额"。` }}
              </a-tag>
              <a-tag 
                v-show="showRemainingBisectButton(model, field)" 
                color="orange"
                class="flex-tag"
              >
                {{ `"内部${ isCommission ? '委托' : '分包' }金额"扣减锁定数据的"内部分包合同对应金额"累计和后，再按"自动分摊"分配。` }}
              </a-tag>
            </div>
            <div class="btn-group">
              <div v-show="showAutoBisectButton(model, field)">
                <a-button
                  :disabled="isAutoBisectDisabled(model)"
                  @click="autoBisect(model, field)"
                >自动分摊</a-button>
              </div>
              <div v-show="showRemainingBisectButton(model, field)">
                <a-button
                  @click="remainingBisect(model, field)"
                >剩余分摊</a-button>
              </div>
            </div>
          </div>
          <div style="padding: 0 0 1rem 0;">
            <BasicTable :dataSource="model[field]" :columns="tableColumns" @register="registerTable">
              <!-- 分包比例统一输入==需要隐藏 -->
              <template #bodyCell="{ column, index, record }">
                <template v-if="column.key === 'amountPercentage'">
                  <span v-if="isReadonly(record)">
                    {{ formatPercent(record.amountPercentage/100) }}
                  </span>
                  <a-form-item 
                    v-else
                    label-width="0px" 
                    :name="['contractPaymentTerms', index, column.dataIndex]" 
                    :rules="[required, isPN, ...isSmall(100, '100%')]"
                    validateFirst
                  >
                    <JnpfInput
                      type="number"
                      :disabled="isReadonly(record)"
                      v-model:value="record.amountPercentage"
                      placeholder='请输入分包比例'
                      style="width: 100%"
                      @change="val => change(val, { record, column, index })"
                    />
                  </a-form-item>
                </template>
                <template v-if="column.key === 'packageAmount'">
                  <div :class="['align-right', isNumber(record.packageAmount) ? '' : 'gray']">
                    {{ isNumber(record.packageAmount) ? formatPrice(parseFloat(record.packageAmount)) : '输入分包比例系统自动计算' }}
                  </div>
                </template>
              </template>
            </BasicTable>
          </div>
        </template>
        <template #contractMaterialsList="{ model, field }">
          <div class="title-tip">
            <TableTitle title="交付清单明细" />
          </div>
          <BasicTable
            ref="tableRef"
            :immediate="false"
            :dataSource="model[field]"
            @register="registerDeliveryListTable"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'unitOfMeasurement'">
                <span>{{ record.children ? '--' : record.unitOfMeasurement }}</span>
              </template>
              <template v-if="column.key === 'unitPrice'">
                <span>{{ record.children ? '--' : formatPrice(record.unitPrice) }}</span>
              </template>
              <template v-if="column.key === 'taxRate'">
                <span>{{ record.children ? '--' : formatPercent(record.taxRate) }}</span>
              </template>
              <template v-if="column.key === 'quantity'">
                <span>{{ record.children ? '--' : record.quantity }}</span>
              </template>
            </template>
          </BasicTable>
        </template>
      </BasicForm>
    </div>
    <div v-if="isEdit" class="IlmsForm-footer">
      <a-space>
        <a-button v-show="canReturn" :loading="loading" @click="viewTasks">上一步</a-button>
        <a-button v-show="isEdit" :loading="loading" @click="staging">暂存</a-button>
        <a-button v-show="isEdit" :loading="loading" @click="submit" type="primary">提交</a-button>
      </a-space>
    </div>
    <!-- 是分包&&审批通过&&是最新版本的数据，有推送按钮 -->
    <div v-if="canPush" class="IlmsForm-footer">
      <a-space>
        <a-button type="primary" :loading="loading" @click="contractPush">推送</a-button>
      </a-space>
    </div>
  </div>
</template>

<script name="internalOperationsForm" setup>
  import { useMessage } from '@/hooks/web/useMessage';
  import { JnpfInput } from '@/components/Jnpf';
  import { TableTitle } from '@/components/Wcomp';
  import { useForm, BasicForm } from '@/components/Form';
  import { useTable, BasicTable, TableAction } from '@/components/Table';
  import { useUserStore } from '@/store/modules/user';
  import { canEdit } from '@/utils/toolW';
  import { required, isPN, isSmall } from '@/utils/rules';
  import { formatPrice, formatPercent } from '@/utils/priceUtil';
  import { saveOrUpdatePackageContract, savePackageContractDraft, packageSubmit, trustSubmit } from '@/views/project/internalOperations/common/api';
  import { tableOptions, columnsList } from '@/views/project/internalOperations/common/deliveryListConfig';
  import { getTableSchema, getFormSchema, getAttachmentSchema } from '@/views/project/internalOperations/common/formConfig';
  import MerchantSelect from '@/views/mdm/merchant/select.vue';
  import PartyBStaffSelect from '@/views/project/internalOperations/components/PartyBStaffSelect.vue';

  const props = defineProps({
    config: {
      type: Object,
      default: () => {},
    },
    commission: { // 是否是委托（true是，flase否）
      type: Boolean,
      default: false,
    },
    contractData: {
      type: Object,
      default: () => {},
    },
    masterContractData: {
      type: Object,
      default: () => {},
    },
  });

  // setPageLoad：设置流程加载状态
  const emit = defineEmits(['setPageLoad', 'eventReceiver']);
  const { createMessage } = useMessage();

  const formRef = ref(), tableRef = ref();
  const pushData = ref({}); // 推送的数据
  const internalContractData = ref({}), // 本合同数据-副本
        partyBId = ref(''); // 本合同乙方id
  const tableColumns = ref([]),
        lockTotalAmount = ref(''), // 支付条款里锁定明细金额累计和
        totalInitializeAmount = ref(''); // 支付条款的明细金额累计和
  const loading = ref(false);
  const isEdit = ref(false),
        isChange = ref(false), // 是否是填写了分包比例
        isInitialized = ref(false), // 是否完成初始化
        spStatus = ref('');

  const isFlow = computed(() => {
    return props.config?.flowId;
  });

  const isReadonly = computed(() => {
    return (record) => !isEdit.value || record.lockStatus == 2;
  });
  const isFlowCommission = ref(false); // 流程中的委托标识

  // 接收父组件数据
  const current = inject('current');
  const saveAll = inject('saveAll');
  const initTasks = inject('initTasks');
  const initTable = inject('initTable');
  const canReturn = inject('canReturn');
  const lastVersion = inject('lastVersion', true);
  const openContractPush = inject('openContractPush');
  const isMine = inject('isMine');
  const projectInfo = inject('projectInfo', ref({}));

  const [ registerTable, { getDataSource } ] = useTable({
    bordered: true, // 边框
    showTableSetting: false,
    pagination: false,
  });

  const [ registerDeliveryListTable, 
      { 
        setSelectedRowKeys,
        setTableData
      }
    ] = useTable({
    columns: columnsList,
    rowKey: 'materialsCode',
    ...tableOptions,
  });

  const [
    registerForm,
      { 
        validateFields,
        setFieldsValue,
        getFieldsValue,
        updateSchema,
        clearValidate,
        resetSchema
      } 
    ] = useForm({
    schemas: [],
    layout: 'vertical', // label的排在上面
    labelWidth: 190,
    baseColProps: { span: 12 },
    showActionButtonGroup: false,
    compact: true,
    colon: true,
  });
  
  const viewTasks = () => {
    current.value -= 1;
    initTable();
  };

  const staging = async (isPrompt = true) => {
    await validateFields();
    loading.value = true;
    try {
      const { contractCode } = projectInfo.value;
      let where = {
        contractCode,
        state: '0', // 暂存的状态
      };

      let data = getFieldsValue();
      // 判断是委托还是分包，对应处理数据
      let getCommission = props.commission;
      if (data.spStatus == '3') getCommission = isCommission.value;
      
      if(getCommission){
        where.contractTrustVoList = [{
          ...data,
          contractTrustPaymentInfos: data.contractPaymentTerms,
        }];
      }else{
        where.contractPackageVoList = [{
          ...data,
          contractPaymentInfosPackage: data.contractPaymentTerms,
        }];
      };
      // console.log("3.1-暂存传参-where", where);
      const res = await saveOrUpdatePackageContract(where);
      // console.log("3.2-暂存成功-res", res);
      if(res.code==200) {
        // 重置状态
        isChange.value = false;
        isInitialized.value = false;
        if(isPrompt) createMessage.success('暂存成功！');
      }
    } finally {
      loading.value = false;
    };
  };

  const submit = async () => {
    const data = unref(getFieldsValue());
    if(data.spStatus == '3') {
      // 先暂存，再提交
      await staging(false);
      let getCommission = isCommission.value;
      let api = getCommission ? trustSubmit : packageSubmit;
      const res = await api(data.fid);
      // console.log("3.3-被拒绝后，再提交成功-res", res);
      if(res.code == 200) {
        createMessage.success('提交成功！');
        initTasks(); // 刷新
      }
      return;
    }
    saveAll();
  };

  const isNumber = (num) => {
    let where = num != null && !isNaN(parseFloat(num)) && isFinite(num)
    return where;
  };

  const contractPush = () => {
    const formData = getFieldsValue();
    let file = formData.contractAnnexDraft;
    if(!file) return createMessage.warning('推送前，请先上传合同扫描附件！');
    openContractPush(true, pushData.value);
  };
  
  const updateFormValues = async (newMaster, newContract) => {
    if (isChange.value) return;
    // 本合同乙方id【分包contractSigningPartyB、委托deptId】
    partyBId.value = newContract.contractSigningPartyB || newContract.deptId;
    let treeList = newContract?.contractMaterialsTrustVoList || newContract?.contractMaterialsPackageList || [];
    // 构建新的表单值
    const value = {
      // 对应委托信息or分包信息
      ...newContract,
      // 主合同信息(赋值)
      originalContractCode: newMaster.contractCode, // 主合同编号，重命名，避免和委托分包的合同编码命名相同；
      contractName: newMaster.contractName,
      contractSigningPartyAName: newMaster.contractSigningPartyAName,
      originalContractPartyB: newMaster.contractSigningPartyB, // 主合同签署乙方，重命名，避免和分包乙方名称相同；
      packageContractSigningPartyA: newMaster.contractSigningPartyB, // 本合同签署乙方==分包甲方；
      commissionContractSigningPartyA: newMaster.contractSigningPartyB, // 本合同签署乙方==委托甲方；
      constructionContentDirection: newContract.constructionContentDirection,
      acquisitionMethod: newMaster.acquisitionMethod,
      projectAttribute: newMaster.projectAttribute,
      strategicUnit: newMaster.strategicUnit,
      projectCategory: newMaster.projectCategory,
      projectType: newMaster.projectType,
      accountManagerName: newMaster.accountManagerName,
      signingDate: newMaster.signingDate,
      projectAddress: newMaster.projectAddress,
      projectImplementationResponsibleUnit: newMaster.projectImplementationResponsibleUnit,
      qualityWarrantyPeriod: newMaster.qualityWarrantyPeriod,
      contractPeriod: [newMaster.startDate, newMaster.endDate],
      startDate: newMaster.startDate,
      endDate: newMaster.endDate,
      // 处理特殊数据（支付条款重命名，方便使用一样的插槽;分包合同的附件信息）
      contractPaymentTerms: newContract?.contractTrustPaymentInfos || newContract?.contractPaymentInfosPackage || [],
      contractMaterialsList: treeList,
      contractDraft: (!isCommission.value)&&newContract.contractDraft ? newContract.contractDraft : [],
      contractAnnexDraft: (!isCommission.value)&&newContract?.contractAnnexDraft
        ? [newContract.contractAnnexDraft] : [], // 避免附件上传不隔离问题【A分包上传附件1，B分包也显示】
    };
    spStatus.value = newContract.spStatus;
    // 是客户经理&&审批状态有权限
    isEdit.value = isMine?.value && canEdit(newContract.spStatus);
    // 计算锁定行明细金额累计和
    lockTotalAmount.value = value.contractPaymentTerms.filter(item =>
      item.lockStatus == 2 // 过滤出锁定行数据
    ).reduce((sum, item) => 
      sum + (parseFloat(item.packageAmount) || 0)
    , 0);
    
    // 计算明细金额累计和
    totalInitializeAmount.value = value.contractPaymentTerms.reduce((sum, item) =>
      sum + (parseFloat(item.initializeAmount) || 0)
    , 0);
    await getSchemas(); // 重新生成schema，刷新内部分包/委托金额编辑权限
    await nextTick();
    setFieldsValue(value);
    clearValidate();
  };

  watch(
    () => props.contractData,
    (newContract) => {
      if (!newContract || Object.keys(newContract).length === 0) return;
      // 仅首次||非用户输入，更新内部数据
      if (!isInitialized.value || !isChange.value) {
        internalContractData.value = { ...newContract };
        isInitialized.value = true;
      }
    },
    { deep: true, immediate: true }
  );

  watch(
    () => props.masterContractData,
    async (newMaster) => {
      if (!newMaster || Object.keys(newMaster).length === 0) return;
      await nextTick();
      updateFormValues(newMaster, internalContractData.value);
    },
    { deep: true, immediate: true }
  );

  const onUploadFileChange = async () => {
    const formData = unref(getFieldsValue());
    let file = formData.contractAnnexDraft;
    try {
      if(!file) return;
      let where = {
        contractId: formData.fid,
        contractAnnexDraft: file ? file : [],
      };
      let res = await savePackageContractDraft(where);
      if (res.code==200) {
        createMessage.success('合同扫描件上传成功！');
        setFieldsValue({ contractAnnexDraft: file }); // 回显文件
      }
    } catch (error) {
      const errorMsg = file ? '合同扫描件上传失败！' : '附件删除失败！';
      createMessage.error(errorMsg);
    };
  };

  // 自动分摊
  const showAutoBisectButton = (model, field) => {
    if (!isEdit.value) return false;
    // 支付条款是否存在锁定行
    const paymentTerms = model[field] || [];
    const hasLockedRow = paymentTerms.some(item => item.lockStatus == 2);
    if (hasLockedRow) return false;
    // 获取金额值，处理空值/非数字情况
    const getAmount = (field) => parseFloat(model[field] || 0);
    
    // 根据委托类型判断金额条件
    if (isCommission.value) return getAmount('trustAmountTax') > 0;
    return getAmount('amountTaxIncluded') > 0;
  };

  // 自动分摊按钮
  const isAutoBisectDisabled = (model) => {
    // 内部分包/委托金额不能大于明细金额和
    const condition = model['amountTaxIncluded'] > totalInitializeAmount.value || 
                    model['trustAmountTax'] > totalInitializeAmount.value;
    return condition;
  };

  const autoBisect = (model, field) => {
    const paymentTerms = model[field];
    let type = isCommission.value ? 'trustAmountTax' : 'amountTaxIncluded';
    let typeStr = isCommission.value ? '委托' : '分包';
    const totalAmount = parseFloat(model[type]);
    
    // 验证数据有效性
    if (totalAmount <= 0 || totalInitializeAmount.value <= 0) {
      createMessage.warning(`内部${typeStr}金额、支付条款里明细金额累计金额必须大于0！`);
      return;
    }

    // 计算统一比例（百分比，保留2位小数）
    const uniformRatio = ((totalAmount / totalInitializeAmount.value) * 100).toFixed(2);

    let allLength = paymentTerms.length - 1;
    // 更新表格数据
    let totalAmountExcludeLast = 0;
    const tableValues = paymentTerms.map((item, index) => {
      // 明细金额A
      const initializeAmount = parseFloat(item.initializeAmount) || 0;

      let where = { ...item };
      if(allLength!=index) { // 前面的比例、分包金额
        // 分包金额C
        let packageAmount = ((initializeAmount * uniformRatio) / 100).toFixed(2);
        // 计算：除了最后一项分包金额的累计和allC-lastC
        totalAmountExcludeLast += parseFloat(packageAmount);

        where.amountPercentage = uniformRatio;
        where.packageAmount = packageAmount;
      }else{ // 最后一项的比例、分包金额
        // 最后一项的分包金额lastC，扣减得到；
        let lastAmount = (totalAmount - totalAmountExcludeLast);
        // 分包比例B=分包金额C/明细额A；
        let lastRatio = (lastAmount / initializeAmount * 100).toFixed(2);
        where.amountPercentage = lastRatio;
        where.packageAmount = lastAmount;
      }
      return where;
    });

    // 计算分包金额总和【应与合同总额相等】
    const totalPackageAmount = tableValues.reduce((sum, item) =>
      sum + (parseFloat(item.packageAmount) || 0)
    , 0);

    isChange.value = true;
    // 更新表单字段
    setFieldsValue({
      contractPaymentTerms: tableValues,
      [type]: totalPackageAmount.toFixed(2),
    });
    clearValidate();
  };

  // 剩余分摊
  const showRemainingBisectButton = (model, field) => {
    if (!isEdit.value) return false;
    // 支付条款是否存在锁定行
    const paymentTerms = model[field] || [];
    const hasLockedRow = paymentTerms.some(item => item.lockStatus == 2);
    // 是否存在非锁定行
    const hasUnlockedRow = paymentTerms.some(item => item.lockStatus != 2);
    if (!hasUnlockedRow) return false;
    // 金额有效性检查
    const getAmount = (field) => parseFloat(model[field] || 0);

    // 只有同时存在锁定和非锁定行，且金额>0时，才显示按钮
    return hasLockedRow && hasUnlockedRow && (
      isCommission.value
        ? getAmount('trustAmountTax') > 0 
        : getAmount('amountTaxIncluded') > 0
    );
  };

  const remainingBisect = (model, field) => {
    const paymentTerms = model[field];
    let type = isCommission.value ? 'trustAmountTax' : 'amountTaxIncluded';
    let typeStr = isCommission.value ? '委托' : '分包';
    const totalAmount = parseFloat(model[type]);
    
    // 验证数据有效性
    if (totalAmount <= 0) {
      createMessage.warning(`内部${typeStr}金额必须大于0！`);
      return;
    }

    // 步骤1: 分离锁定行和非锁定行
    const lockedRows = paymentTerms.filter(item => item.lockStatus == 2);
    const unlockedRows = paymentTerms.filter(item => item.lockStatus != 2);
    
    // 步骤2: 计算锁定行的总金额（这些金额不会变动）
    const lockedAmount = lockedRows.reduce((sum, item) => 
      sum + (parseFloat(item.packageAmount) || 0), 0);
    
    // 步骤3: 计算剩余需要分摊的金额
    const remainingAmount = totalAmount - lockedAmount;
    
    // 步骤4: 计算非锁定行的明细金额总和
    const unlockedTotalAmount = unlockedRows.reduce((sum, item) => 
      sum + (parseFloat(item.initializeAmount) || 0), 0);
    
    if (unlockedTotalAmount <= 0) {
      createMessage.warning(`非锁定行的明细金额总和必须大于0！`);
      return;
    }

    // 步骤5: 计算剩余分摊的统一比例
    const uniformRatio = ((remainingAmount / unlockedTotalAmount) * 100).toFixed(2);
    
    // 步骤6: 更新非锁定行的分包比例和分包金额
    let totalAmountExcludeLast = 0;
    const updatedUnlockedRows = unlockedRows.map((item, index) => {
      const initializeAmount = parseFloat(item.initializeAmount) || 0;
      
      // 最后一项特殊处理
      if (index === unlockedRows.length - 1) {
        const lastAmount = remainingAmount - totalAmountExcludeLast;
        const lastRatio = (lastAmount / initializeAmount * 100).toFixed(2);
        return {
          ...item,
          amountPercentage: lastRatio,
          packageAmount: lastAmount.toFixed(2)
        };
      }
      
      // 其他项按比例计算
      const packageAmount = (initializeAmount * uniformRatio / 100).toFixed(2);
      totalAmountExcludeLast += parseFloat(packageAmount);
      
      return {
        ...item,
        amountPercentage: uniformRatio,
        packageAmount
      };
    });

    // 步骤7: 合并锁定行和更新后的非锁定行
    const finalRows = [...lockedRows, ...updatedUnlockedRows];
    
    // 步骤8: 更新表单字段
    setFieldsValue({
      contractPaymentTerms: finalRows,
      [type]: totalAmount.toFixed(2) // 保持总金额不变
    });
    
    clearValidate();
  };

  const change = (value, { record }) => {
    // 确保输入值有效
    const percentage = parseFloat(value) || 0;

    // 计算当前明细分包金额 = 明细金额 × 分包比例%
    if (record.initializeAmount) {
      const initializeAmount = parseFloat(record.initializeAmount);
      record.packageAmount = (initializeAmount * percentage / 100).toFixed(2);
    }
    
    // 获取所有明细数据
    const tableValues = getDataSource();
    
    // 计算所有分包金额总和
    const totalPackageAmount = tableValues.reduce((sum, item) => {
      return sum + (parseFloat(item.packageAmount) || 0);
    }, 0);
    
    isChange.value = true;
    let type = isCommission.value ? 'trustAmountTax' : 'amountTaxIncluded';
    // 更新合同总额为分包金额总和
    setFieldsValue({
      [type]: totalPackageAmount.toFixed(2),
      contractPaymentTerms: tableValues,
    });
  };

  // 最终使用的委托标识（优先流程判断）
  const isCommission = computed(() =>
    isFlow.value ? isFlowCommission.value : props.commission
  );

  // 推送按钮权限
  const canPush = computed(() =>
    !isCommission.value && spStatus.value==2 && lastVersion.value && isMine.value
  );

  // 是否含有锁定数据
  const hasUnlockedRow = computed(() => {
    const paymentTerms = 
      internalContractData.value?.contractPaymentInfosPackage || 
      internalContractData.value?.contractTrustPaymentInfos || [];
    return paymentTerms.some(item => item.lockStatus != 2);
  });

  // 内部分包/委托金额，能否编辑
  const isEditTotalAmount = computed(() => 
    isEdit.value && hasUnlockedRow.value
  );

  const amountPercentageChange = async (val) => {
    const tableData = getFieldsValue()?.contractPaymentTerms || [];
    // 计算每行金额
    const newTableData = tableData.map(item => ({
      ...item,
      amountPercentage: val, // 同步比例值
      packageAmount: item.initializeAmount
        ? (item.initializeAmount * val / 100).toFixed(2) 
        : '',
    }));

    // 更新表格数据
    setFieldsValue({ contractPaymentTerms: newTableData });
  };

  const getSchemas = async () => {
    // 支付条款表格
    tableColumns.value = await getTableSchema();
    const formSchema = await getFormSchema(
      isCommission,
      isEdit,
      amountPercentageChange,
      totalInitializeAmount,
      lockTotalAmount,
      isEditTotalAmount,
    );
    let allSchema = [
      ...formSchema,
      {
        field: 'contractPaymentTerms',
        component: 'Input',
        wrapperCol: { span: 24 },
        slot: 'contractPaymentTerms',
        colProps: { span: 24 },
      },
      {
        field: 'contractMaterialsList',
        component: 'Input',
        wrapperCol: { span: 24 },
        slot: 'contractMaterialsList',
        colProps: { span: 24 },
      },
      ...(isCommission.value ? [] : getAttachmentSchema(isEdit)),
    ];
    resetSchema(allSchema);
  };

  const init = async (masterContractInfo, contractInfo) => {
        await getSchemas();
    updateFormValues(masterContractInfo, contractInfo);
  };

  onMounted(() => {
        // 判断是否在流程审批
    emit('setPageLoad', false);
    if(isFlow.value){
      const config = unref(props.config);
      let formData = config?.formData;
      if(formData?.contractPackageVo) {
        isFlowCommission.value = false;
      }else if(formData?.contractTrustVo){
        isFlowCommission.value = true;
      }
      let contractData = formData?.contractPackageVo || formData?.contractTrustVo || {};
      internalContractData.value = contractData; // 流程页面，props.contractData数据为空
      pushData.value = {
        ...formData?.salesProjectContractVo, 
        ...contractData,
      };
      init(formData?.salesProjectContractVo, contractData);
    }else{
      pushData.value = {
        ...props.masterContractData, 
        ...props.contractData,
      };
      init(props.masterContractData, props.contractData);
    }
  });

  // 流程里审批的调用
  const dataFormSubmit = (actionType) => {
    let formData = getFieldsValue();
    emit('eventReceiver', formData, actionType);
  };

  defineExpose({
    validateFields,
    getFieldsValue,
    dataFormSubmit,
  });
</script>

<style scoped>
  @import url('@/design/IlmsForm.less');

  /* 设置表格高度根据内容自适应 */
  :deep(.ant-table-body) {
    height: auto !important;
    max-height: none !important;
  }

  .align-right {
    text-align: right;
  }

  .gray {
    color: #d9d9d9;
  }

  .title-tip {
    width: 100%;
    display: flex;
    align-items: center;
  }

  .tip-container {
    flex: 1;
    text-align: end;
    margin-bottom: 4px;

    .flex-tag {
      white-space: normal; /* 允许换行 */
    }
  }

  .btn-group {
    margin-bottom: 4px;
  }
</style>
